<template>
    <el-container class="gross-profit-calculator">
		<el-header ref="pageHeaderRef" class="page-header">
			<div class="title-area">
				<h1 class="page-title">澳玛小红书投放评估工具</h1>
				<span class="version-info">版本号: 1.1</span>
				<span class="upgrade-info">时间: 2025/07/21</span>
			</div>
            <div class="user-info">
                <span>{{ userInfo?.organizationName || '用户' }}</span>
                <el-button type="danger" size="small" @click="handleLogout">退出登录</el-button>
            </div>
		</el-header>

		<el-main class="main-content">
			<!-- <el-row :gutter="20"> -->
				<el-card class="!border-none mt-4" shadow="never">
                    <div ref="buttonAreaRef" v-if="userInfo?.type != 1">
                        <el-button type="primary" @click="handleImport" >
                            导入
                        </el-button>
                        <el-button type="primary" @click="downloadTemplate" :loading="exportLoading">
                            下载导入模板
                        </el-button>
                        
                        
                    </div>
                    <div style="margin-top: 20px;" v-loading="pager.loading">
                        <div>
                            <el-table :data="pager.lists" :height="tableHeight" style="width: 100%;" border :row-class-name="getRowClassName" header-cell-class-name="headerClass">
                                <el-table-column prop="organizationName" label="机构" width="120" align="center"/>
                                <el-table-column prop="title" label="标题" width="300" align="center"/>
                                <el-table-column prop="releaseDate" label="发布时间" width="150" align="center">
                                    <template #default="{ row }">
                                        {{ timeFormat(row.releaseDate, 'yyyy-mm-dd') }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="type" label="内容类型" width="100" align="center"/>
                                <el-table-column prop="updateDate" label="最后更新时间" width="150" align="center">
                                    <template #default="{ row }">
                                        {{ timeFormat(row.updateDate, 'yyyy-mm-dd') }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="lookCount" label="观看量" width="80" align="center"/>
                                <el-table-column prop="perCapitaLookTime" label="人均观看时长" width="120" align="center"/>
                                <el-table-column prop="giveCount" label="点赞量" width="80" align="center"/>
                                <el-table-column prop="collectCount" label="收藏量" width="80" align="center"/>
                                <el-table-column prop="commentCount" label="评论量" width="80" align="center"/>
                                <el-table-column prop="shareCount" label="分享量" width="80" align="center"/>
                                <el-table-column prop="addFansCount" label="涨粉量" width="80" align="center"/>
                                <el-table-column prop="interactionCount" label="总互动" width="80" align="center"/>
                                <!-- <el-table-column label="是否第一次投放" width="150" align="center">
                                    <template #default="{ row }">
                                        <el-tag :type="row.isFirstLaunch ? 'success' : 'info'">
                                            {{ row.isFirstLaunch ? '是' : '否' }}
                                        </el-tag>
                                    </template>
                                </el-table-column> -->
                                <!-- <el-table-column label="状态" width="120">
                                    <template #default="{ row }">
                                        <el-tag :type="getStatusType(row.status)">
                                            {{ getStatusText(row.status) }}
                                        </el-tag>
                                    </template>
                                </el-table-column> -->
                                <el-table-column prop="firstDeployTrafficDate" label="第一次投流日期" width="150" align="center">
                                    <template #default="{ row }">
                                        {{ row.firstDeployTrafficDate?timeFormat(row.firstDeployTrafficDate, 'yyyy-mm-dd'):'' }}
                                    </template>
                                </el-table-column>
                                <el-table-column prop="firstDeployTrafficInteractionCount" label="投流前总互动量" width="128" align="center"/>
                                <el-table-column prop="newInteractions" label="新增互动量" width="100" align="center">
                                    <template #default="{ row }">
                                        {{ row.isFirstDeployTraffic == 30 ? row.interactionCount - row.firstDeployTrafficInteractionCount : '' }}
                                    </template>
                                </el-table-column>
                                <el-table-column label="投放状态" width="150" align="center">
                                    <template #default="{ row }">
                                        <!-- <el-select v-if="row.isFirstDeployTraffic && row.isFirstDeployTraffic >= 20" v-model="row.isFirstDeployTraffic" placeholder="请选择" :disabled="row.status === 20"
                                            @change="handleAuditChange(row, $event)" style="width: 100%">
                                            <el-option label="待审核" :value="20" :disabled="true"/>
                                            <el-option label="已投放" :value="30" />
                                            <el-option label="不投放" :value="40" />
                                        </el-select>
                                        <span v-else></span> -->
                                        <span>{{ getAuditText(row.isFirstDeployTraffic) }}</span>
                                    </template>
                                </el-table-column>
                                <el-table-column label="开口量" width="200" align="center" prop="openingQuantity">
                                    <!-- <template #default="{ row }">
                                        <div class="opening-amount-container">
                                            <el-input :ref="(el: any) => setInputRef(el, row.id)" v-model="row.openingQuantity"
                                                placeholder="请输入开口量" @input="handleOpeningAmountChange(row)" style="width: 120px" class="opening-amount-input"/>
                                            <el-button v-if="row.openingQuantity && row.openingQuantity.toString()?.trim() !== ''" type="primary"
                                                size="small" @click="saveOpeningAmount(row)" style="margin-left: 8px">
                                                保存
                                            </el-button>
                                        </div>
                                    </template> -->
                                </el-table-column>
                                <el-table-column label="操作" width="300" fixed="right" align="center" >
                                    <!-- v-if="userInfo?.type == 1" -->
                                    <template #default="{ row }">
                                        <el-button  type="primary" v-if="row.isFirstDeployTraffic == 20"
                                            @click="handleAuditChange(row, 30)">
                                            投放
                                        </el-button>
                                        <el-button  type="danger" v-if="row.isFirstDeployTraffic == 20"
                                            @click="handleAuditChange(row, 40)">
                                            不投放
                                        </el-button>
                                        <el-button  type="primary" v-if="row.isFirstDeployTraffic == 30"
                                            @click="changeOpeningQuantity(row.id)">
                                            更改开口量
                                        </el-button>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                        
                        <div ref="paginationRef" class="flex justify-end mt-4" style="width: 100%;display: flex;justify-content: flex-end;margin-top: 20px;">
                            <pagination v-model="pager" @change="getLists" />
                        </div>
                    </div>
                    
                </el-card>
                <templateImport ref="importRef" @uploadSuccessFun="getLists"  />
                
                <!-- 更改开口量弹窗 -->
                <el-dialog
                    v-model="dialogVisible"
                    title="更改开口量"
                    width="400px"
                    :before-close="cancelDialog"
                >
                    <div class="dialog-content">
                        <el-form label-width="80px">
                            <el-form-item label="开口量:">
                                <el-input
                                    v-model="openingQuantityInput"
                                    placeholder="请输入开口量"
                                    type="number"
                                    clearable
                                />
                            </el-form-item>
                        </el-form>
                    </div>
                    <template #footer>
                        <div class="dialog-footer">
                            <el-button @click="cancelDialog">取消</el-button>
                            <el-button type="primary" @click="saveOpeningAmount">保存</el-button>
                        </div>
                    </template>
                </el-dialog>
			<!-- </el-row> -->
		</el-main>
	</el-container>
</template>

<script lang="ts" setup>
import { ref, nextTick, onMounted, onUnmounted, shallowRef, reactive  } from 'vue'
import { ElMessage, ElMessageBox, ElNotification } from 'element-plus'
import type { UploadProps, UploadRawFile } from 'element-plus'
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import feedback from '@/utils/feedback'
import { usePaging } from '@/hooks/usePaging'
import { articleList, articleEdit, articleAudit } from '@/api/port'
import { timeFormat } from '@/utils/validate'
import pagination from '../components/pagination/index.vue'

// 修正导入路径,确保路径正确指向uploadFile.vue组件
import templateImport from '../components/upload/uploadFile.vue' // 导入弹窗
const importRef = shallowRef<InstanceType<typeof templateImport>>()

// 导入弹窗
const handleImport = async () => {
	importRef.value && importRef.value.open()
}

// 下载模板
const downloadTemplate = () => {
    const templateUrl = 'http://101.200.179.69:8990/temp.xlsx'
    const link = document.createElement('a')
    link.href = templateUrl
    link.download = 'template.xlsx'
    link.target = '_blank'
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    // ElMessage.success('模板下载已开始')
}


// 输入框引用
const inputRefs = ref<Record<number, any>>({})

// 设置输入框引用
const setInputRef = (el: any, id: number) => {
    if (el) {
        inputRefs.value[id] = el
    }
}

// 获取状态文本
const getStatusText = (status: number): string => {
    const statusMap: Record<number, string> = {
        1: '待审核',
        2: '待处理',
        3: '待投放'
    }
    return statusMap[status] || '未知状态'
}

// 获取状态标签类型
const getStatusType = (status: number): string => {
    const typeMap: Record<number, string> = {
        1: 'warning',
        2: 'info',
        3: 'success'
    }
    return typeMap[status] || 'info'
}

// 处理投放审核变化
const handleAuditChange = async (row: any, event: any) => {
    console.log(event)
    let label = event == 30 ? '投放' : '不投放'
    await feedback.confirm('您确定要将投放审核改为' + label + '吗？')
    await nextTick()
    const res = await articleAudit({
        articleId: row.id,
        isFirstDeployTraffic: event
    })
    getLists()
    if(res.data.code == 0){
        feedback.msgSuccess('操作成功')
    }else{
        feedback.notifyError_vice(res.data.msg, {
            duration: 0
        })
    }
}
const getAuditText = (status: any): string => {
    const statusMap: Record<number, string> = {
        10: '',
        20: '已达标待审核',
        30: '已投放',
        40: '不投放'
    }
    return statusMap[status] || ''
    // if (row.isFirstDeployTraffic == 20) {
    //     return '待审核'
    // } else if (row.isFirstDeployTraffic == 30) {
    //     return '已投放'
    // } else if (row.isFirstDeployTraffic == 40) {
    //     return '不投放'
    // } else if (row.isFirstDeployTraffic == 10) {
    //     return '未达标'
    // }
}
// 处理开口量输入变化
const handleOpeningAmountChange = (row: any) => {
    // 这里可以添加输入验证逻辑
    console.log(`开口量变化: ${row.openingAmount}`)
}

// 弹窗相关状态
const dialogVisible = ref(false)
const currentRow = ref<any>(null)
const openingQuantityInput = ref('')

// 更改开口量方法
const changeOpeningQuantity = (id: number) => {
    // 找到对应的行数据
    const row = pager.lists.find((item: any) => item.id === id)
    if (row) {
        currentRow.value = row
        openingQuantityInput.value = row.openingQuantity || ''
        dialogVisible.value = true
    }
}

// 保存开口量
const saveOpeningAmount = async () => {
    if (!openingQuantityInput.value || openingQuantityInput.value.trim() === '') {
        ElMessage.warning('请输入开口量')
        return
    }
    try {
        const res = await articleEdit({
            articleId: currentRow.value.id,
            openingQuantity: Number(openingQuantityInput.value)
        })
        console.log(res)
        ElMessage.success('开口量保存成功')
        dialogVisible.value = false
        // 刷新列表
        getLists()
    } catch (error) {
        ElMessage.error('开口量保存失败')
    }
}

// 取消弹窗
const cancelDialog = () => {
    dialogVisible.value = false
    openingQuantityInput.value = ''
    currentRow.value = null
}

// DOM元素引用
const pageHeaderRef = ref<HTMLElement>()
const buttonAreaRef = ref<HTMLElement>()
const tableContainerRef = ref<HTMLElement>()
const paginationRef = ref<HTMLElement>()

// 各部分高度的响应式变量
const headerHeight = ref(70) // 默认值
const buttonAreaHeight = ref(52) // 默认值
const paginationHeight = ref(60) // 默认值
const safetyMargin = ref(40) // 安全边距

// 计算表格最大高度
const calculateTableHeight = () => {
    // 获取实际DOM元素高度
    const actualHeaderHeight = pageHeaderRef.value?.offsetHeight || headerHeight.value
    const actualButtonHeight = buttonAreaRef.value?.offsetHeight || 0
    const actualPaginationHeight = paginationRef.value?.offsetHeight || paginationHeight.value
    
    // 更新响应式变量
    headerHeight.value = actualHeaderHeight
    buttonAreaHeight.value = actualButtonHeight
    paginationHeight.value = actualPaginationHeight
    
    // 计算总的减去高度
    const totalReduceHeight = actualHeaderHeight + actualButtonHeight + actualPaginationHeight + safetyMargin.value + 100 // 40px为额外间距
    
    return `calc(100vh - ${totalReduceHeight}px)`
}

// 表格高度
const tableHeight = ref(calculateTableHeight())

// 重新计算表格高度的方法
const recalculateTableHeight = () => {
    tableHeight.value = calculateTableHeight()
}

const router = useRouter()
const userStore = useUserStore()
const userInfo = ref<any>({})
userInfo.value = userStore.userInfo || JSON.parse(localStorage.getItem('userInfo') || '{}')
console.log(localStorage.getItem('userInfo'))
console.log(userInfo.value)
// 退出登录
const handleLogout = async () => {
    try {
        await ElMessageBox.confirm(
            '确定要退出登录吗？',
            '提示',
            {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }
        )
        // 使用store退出登录
        userStore.logout()
        ElMessage.success('退出登录成功')
        // 跳转到登录页
        router.push('/login')
    } catch {
        // 用户取消退出
    }
}

// 页面加载时初始化用户信息
onMounted(() => {
    userStore.initUserInfo()
    // 等待DOM渲染完成后重新计算表格高度
    nextTick(() => {
        recalculateTableHeight()
    })
    
    // 监听窗口大小变化
    window.addEventListener('resize', recalculateTableHeight)
})

// 组件卸载时清理事件监听
onUnmounted(() => {
    window.removeEventListener('resize', recalculateTableHeight)
})
// 3. 导出处理函数
// 2. 导出加载状态
const exportLoading = ref(false);
const handleExport = async () => {
	// 1. 获取表格数据
	feedback.loading('数据导出中，请稍等');
	// const res = await inforLists({export: 2})
	// const res = await inforLists({page: 1, page_size: 25000})
	feedback.closeLoading()
}
// 获取行类名
const getRowClassName = ({ row }: { row: any }) => {
    if (row.isFirstDeployTraffic == 20) {
        return 'status-pending'
    } else if (row.isFirstDeployTraffic == 30) {
        return 'status-processed'
    }
    return ''
}
// 表格数据
const queryParams = ref({})
const { pager, getLists, resetPage, resetParams } = usePaging({
    fetchFun: articleList,
    params: queryParams.value
})
getLists()

</script>

<style lang="less" scoped>
.gross-profit-calculator {
	/* padding: 20px; */
	background-color: #FAF8F8;
	height: 100vh;
}

.page-header {
	display: flex;
	justify-content: space-between;
	align-items: center;
	margin-bottom: 20px;
	padding: 0;
	/* Override default el-header padding */
	height: auto;
	/* Adjust height */
	background-color: #fff;
	/* Header background for contrast if needed */
	padding: 15px 20px;
	border-radius: 4px;
	box-shadow: 0px 2px 6px 0px rgba(0,0,0,0.08);
}
.title-area {
	display: flex;
	align-items: center;
}

.page-title {
	font-size: 20px;
	/* font-weight: 600; */
	color: #3098F7;
	margin: 0;
}

.version-info,
.upgrade-info {
	font-size: 12px;
	color: #909399;
	margin-left: 15px;
}

.actions-area .el-button {
	margin-left: 10px;
}
// .page-container {
//     min-height: 100vh;
//     background-color: #f5f5f5;
// }

// .page-header {
//     background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
//     color: white;
//     padding: 20px 30px;
//     display: flex;
//     justify-content: space-between;
//     align-items: center;
//     box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);

//     h1 {
//         margin: 0;
//         font-size: 24px;
//         font-weight: 600;
//     }

    .user-info {
        display: flex;
        align-items: center;
        gap: 15px;

        span {
            font-size: 14px;
            opacity: 0.9;
        }
    }
// }

.table-container {
    padding: 20px 30px;
    overflow-x: auto;

    .opening-amount-container {
        display: flex;
        align-items: center;
    }

    .el-table {
        .el-tag {
            font-weight: 500;
        }

        .el-table__cell {
            padding: 8px 0;
            font-size: 12px;
        }

        :deep(.el-table__header-wrapper) {
            .el-table__header {
                th {
                    background-color: #909399 !important;
                    color: white !important;
                    font-weight: 600;
                }
            }
        }

        :deep(.el-table th.el-table__cell) {
            background-color: #909399 !important;
            color: white !important;
        }

        // 待处理状态行样式（青绿色）
        :deep(.status-pending) {
            background-color: #e0f2f1;
        }

        // 已处理状态行样式（浅蓝色）
        // :deep(.status-processed) {
        //     background-color: #e3f2fd !important;
        // }
    }
}
// 待处理状态行样式（青绿色）
:deep(.status-pending) {
    background-color: #e0f2f1;
}
// 已处理状态行样式（浅蓝色）
:deep(.status-processed) {
    background-color: #e3f2fd !important;
}

.excel-upload-container {
  max-width: 600px;
  margin: 30px auto;
}

.upload-progress {
  margin: 15px 0;
}

.upload-btn {
  margin-top: 10px;
}
.el-input__wrapper{
    border: none;
}
:deep(.headerClass){
    background-color: #909399 !important;
    color: #333;
}

// 弹窗样式
.dialog-content {
    padding: 20px 0;
}

.dialog-footer {
    text-align: right;
}

.dialog-footer .el-button {
    margin-left: 10px;
}
</style>